<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
        @returnBack="returnBack"
      >
        <div class="model-panel">
          <div class="model-panel">
            <div class="model-panel-title">
              <p>证照信息</p>
            </div>
            <div class="model-panel-body">
              <page-form
                class="paddingBox order-model-formBox flex_wrap_start_start"
                v-model:ref-obj.sync="formInfo.licenseRef"
                :data="formInfo.data"
                :field-list="formInfo.licenseFieldList"
                :rules="formInfo.rules"
                :label-width="formInfo.labelWidth"
                :list-type-info="listTypeInfo"
              >
                <template v-slot:form-licenseNumber>
                  <el-input
                    class="not-mongolia"
                    type="input"
                    :disabled="true"
                    placeholder="请选择证照"
                    v-model="formInfo.data.licenseNumber"
                  >
                    <template #append>
                      <el-icon @click="openLicenseList"><MoreFilled /></el-icon>
                    </template>
                  </el-input>
                </template>
              </page-form>
            </div>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-g1Value>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择"
                  v-model="formInfo.data.g1Value"
                >
                  <template #append>
                    <el-icon @click="openBarCodeRules"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>

              <template v-slot:form-filePathList>
                <div class="slot-filePathList">
                  <UploadImg
                    multiple
                    :action="action"
                    :title="'附件'"
                    :responseFn="handleResponse"
                    :limit="10"
                    v-model:value="formInfo.data.filePathList"
                  />
                </div>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>控制信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.controlRef"
              :data="formInfo.data"
              :field-list="formInfo.controlFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-expectedUsageTimes>
                <el-input-number
                  v-model="formInfo.data.expectedUsageTimes"
                  controls-position="right"
                  style="minwidth: 100%"
                  :min="1"
                  @change="changeExpectedUsageTimes"
                />
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>挂网信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.spreadRef"
              :data="formInfo.data"
              :field-list="formInfo.spreadFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-networkUnitCoefficient>
                <el-input
                  style="width: 60px"
                  type="input"
                  placeholder=""
                  v-model="formInfo.data.systemUnitCoefficient"
                >
                </el-input>
                {{ unitvalue }}
                <!-- <el-tooltip placement="top" effect="light" content="系统单位">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip> -->
                =
                <el-input
                  style="width: 60px"
                  type="input"
                  placeholder=""
                  v-model="formInfo.data.networkUnitCoefficient"
                >
                </el-input>
                {{ formInfo.data.networkUnit }}
                <!-- <el-tooltip placement="top" effect="light" content="挂网单位">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip> -->
              </template>
              <template v-slot:form-networkPrice>
                <el-input
                  type="input"
                  placeholder="请输入"
                  :disabled="true"
                  v-model="formInfo.data.networkPrice"
                >
                  <template #append>
                    {{
                      formInfo.data.networkUnit
                        ? '元/' + formInfo.data.networkUnit
                        : '-'
                    }}
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>分类信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.classifyRef"
              :data="formInfo.data"
              :field-list="formInfo.classifyFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-productCategoryId>
                <el-tooltip
                  effect="light"
                  :disabled="!formInfo.data.productCategoryValue"
                  :content="formInfo.data.productCategoryValue"
                  placement="top-start"
                >
                  <el-input
                    class="not-mongolia"
                    type="input"
                    :disabled="true"
                    placeholder="请选择分类"
                    v-model="formInfo.data.productCategoryValue"
                  >
                    <template #append>
                      <el-icon @click="openCategoryList"
                        ><MoreFilled
                      /></el-icon>
                    </template>
                  </el-input>
                </el-tooltip>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>医保信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.medicareRef"
              :data="formInfo.data"
              :field-list="formInfo.medicareFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>中标信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.bidderRef"
              :data="formInfo.data"
              :field-list="formInfo.bidderFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-isWinning>
                <div>
                  <el-checkbox
                    v-model="checkedWinning"
                    label="中标"
                    @change="checkedWinningFunc"
                  />
                  <el-checkbox
                    v-model="notCheckedWinning"
                    label="非中标"
                    @change="notCheckedWinningFunc"
                  />
                </div>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>供应商信息</p>
          </div>
          <div class="model-panel-body">
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addSuppler>
                <el-button
                  v-if="$permission('product:relationSupplier')"
                  @click="addSuppler"
                  >添加供应商</el-button
                >
              </template>
              <template v-slot:filter-remove>
                <el-button
                  :disabled="!tableInfo.selections.length"
                  v-if="$permission('product:relationSupplierDel')"
                  @click="remove"
                  >删除供应商</el-button
                >
              </template>
            </page-filter>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <page-table
                v-model:data.sync="tableInfo.data"
                :pager="false"
                :check-box="true"
                :tabIndex="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-supplierName="scope">
                  <p class="slip-edit" @click="showSupplier(scope.row)">
                    {{ scope.row.supplierName || '-' }}
                  </p>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}[price]`"
                    :rules="
                      scope.$index >= 0
                        ? {
                            validator: $validate.positiveMoneyZero,
                            trigger: 'blur',
                          }
                        : {}
                    "
                  >
                    <el-input-number
                      v-model="scope.row.price"
                      controls-position="right"
                      style="minwidth: 100%; margintop: 18px"
                      :precision="
                        $store.state.permission.systemConfig.price_precision
                      "
                      :step="1"
                      :min="0"
                      :disabled="detailId && !isCopy ? true : false"
                      :max="999999999999999"
                      @change="
                        changePrice($event, `data.${scope.$index}.price`)
                      "
                    />
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <SelectLicense
      v-if="selectLicenseInfo.visible"
      @callback="selectLicense"
      :saveEmpty="true"
      v-model:query="selectLicenseInfo.query"
      v-model:showDialog="selectLicenseInfo.visible"
    />
    <SelectBarCodeRules
      v-if="selectBarCodeRules.visible"
      @callback="onSelectBarCodeRules"
      v-model:showDialog="selectBarCodeRules.visible"
      v-model:getCoreProductRule="selectBarCodeRules.rules"
    />
    <SelectProductClassification
      v-if="selectClassification.visible"
      v-model:query="selectClassification.query"
      v-model:show-dialog="selectClassification.visible"
      :saveEmpty="selectClassification.saveEmpty"
      @callback="selectClassificationCallback"
    ></SelectProductClassification>
    <SelectSupplierAddPrice
      v-if="supplierInfo.visible && detailId && !isCopy"
      v-model:show-dialog="supplierInfo.visible"
      :query="supplierInfo.query"
      :check-box="true"
      :highlight-row="false"
      :api="supplierInfo.api"
      @callback="supplierCallback"
    />
    <SelectSupplier
      v-if="supplierInfo.visible && (!detailId || isCopy)"
      v-model:show-dialog="supplierInfo.visible"
      :query="supplierInfo.query"
      :check-box="true"
      :highlight-row="false"
      :api="supplierInfo.api"
      @callback="supplierCallback"
    />
  </div>
</template>

<script setup name="productModify">
import {
  createProduct,
  validateNetworkInfoDuplicated,
  getBrandAll,
  getProductById,
  getProductCategoryTree,
  getUnitAll,
  updateProduct,
  getCoreCodeStatus,
  getCoreSystemConfigAll,
  getSupplierProductAll,
  productsRelationSupplier,
  productsRelationSupplierDel,
  supplierProductsUpdateBatchListByPost,
  setSupplierProductDefault,
  getSupplierPage,
} from '@/api/core'
import SelectBarCodeRules from '../components/SelectBarCodeRules/index'
import SelectSupplier from '@/components/SelectSupplier/index'
import SelectSupplierAddPrice from '@/components/SelectSupplier/SelectSupplierAddPrice'
import axios from 'axios'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const store = useStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  detailId: {
    type: [String, Number],
  },
  title: {
    type: String,
  },
  type: {
    type: String,
  },
  isCopy: {
    type: Boolean,
  },
})
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
let checkFrequency = (rule, value, callback) => {
  let minutes = formInfo.value.data.systemUnitCoefficient
  console.log(minutes, value)
  if (!value || !minutes) {
    callback(new Error('请输入单位比例'))
  }
  callback()
}
const formInfo = ref({
  ref: null,
  licenseRef: null,
  controlRef: null,
  spreadRef: null,
  classifyRef: null,
  medicareRef: null,
  bidderRef: null,
  systemConfig: {},
  data: {
    chargeTimes: 1,
    code: '',
    networkUnit: '',
    needLicense: 1,
    expectedUsageTimes: 1,
    hospitalExpectedUsageTimes: 1,
    unitConvertCoefficient: 1,
    putShelfStatus: 1,
    // importantHighMaterial:
    //   store.state.permission.systemConfig.is_need_important_high_material,
    productNearlyEffective:
      store.state.permission.systemConfig.product_nearly_effective,
    qtyOperateMode: '',
    isConsignment: 0,
    withOperateTable: 0,
    isCollectivePurchase: 0,
    systemUnitCoefficient: '',
  },
  formDisabled: false,
  delFiledList: [],
  fieldList: [
    {
      label: '通用名称',
      value: 'commonName',
      type: 'input',
      required: true,
      maxlength: 200,
    },
    { label: '编码', value: 'code', type: 'input', show: true },
    { label: 'his编码', value: 'hisCode', type: 'input', show: true },
    { label: '别名', value: 'alias', type: 'input' },
    { label: '助记符', value: 'mnemonic', type: 'input' },
    {
      label: '产品类型',
      value: 'productType',
      type: 'select-model',
      clearable: true,
      checkDefault: false,
      code: 'new_product_type',
      labelTip:
        '普通记账耗材：医院直接向患者收费的项目<br/>普通不记账耗材：医院科室内部使用不直接向患者收费的项目',
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
      required: true,
    },
    {
      label: '型号',
      value: 'modelNumber',
      type: 'input',
    },
    { label: '包装规格', value: 'packingSpecification', type: 'input' },
    {
      label: '计量单位',
      value: 'unitId',
      type: 'select',
      required: true,
      list: 'unitList',
      filterable: true,
    },
    {
      label: '数量操作模式',
      value: 'qtyOperateMode',
      show: true,
      type: 'select-model',
      clearable: true,
      onlyShowOption: computed(() => {
        let str = proxy.$store.state.permission.systemConfig.qty_operate_mode
        if (str === 0) {
          return ['0']
        }
        return proxy.$fn.splitArr(str)
      }),
      code: 'qty_operate_mode',
    },
    {
      label: '单位换算系数',
      value: 'unitConvertCoefficient',
      type: 'number',
      min: 1,
      show: true,
      disabled: props.detailId && !props.isCopy ? true : false,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'new_enabled_type',
      required: true,
    },

    {
      label: '条码类型',
      value: 'codeType',
      type: 'select-model',
      code: 'code_type',
      onlyShowOption: computed(() => {
        let str = proxy.$store.state.permission.systemConfig.code_type_support
        if (str === 0) {
          return ['0']
        }
        return proxy.$fn.splitArr(str)
      }),
      checkDefault: false,
    },
    { label: '原厂主码', value: 'mainCode', show: true, type: 'input' },

    {
      label: '上架状态',
      value: 'putShelfStatus',
      type: 'radio-model',
      code: 'put_down_shelf',
    },
    { label: '原厂码规则', value: 'g1Value', type: 'slot', show: true },
    {
      label: '产品长度(cm)',
      value: 'productLength',
      type: 'number',
      precision: 2,
      min: 1,
    },
    {
      label: '产品宽度(cm)',
      value: 'productWidth',
      precision: 2,
      type: 'number',
      min: 1,
    },
    {
      label: '产品高度(cm)',
      value: 'productHeight',
      precision: 2,
      type: 'number',
      min: 1,
    },

    {
      label: '存储条件',
      value: 'storageCondition',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      showDetail: true,
    },
    {
      label: '创建时间',
      value: 'createTime',
      type: 'input',
      showDetail: true,
    },
  ],
  licenseFieldList: [
    {
      label: '证号必填',
      value: 'needLicense',
      type: 'radio-model',
      code: 'needLicense_type',
      required: true,
      show: true,
    },
    {
      label: '证号',
      value: 'licenseNumber',
      type: 'slot',
      required: true,
    },
    {
      label: '证照名称',
      value: 'licenseName',
      type: 'input',
      disabled: true,
      placeholder: false,
      maxlength: 200,
    },
    {
      label: '英文名称',
      value: 'enName',
      type: 'input',
      disabled: true,
      placeholder: false,
      maxlength: 200,
    },
    {
      label: '证照生效日期',
      value: 'licenseBeginDate',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '证照失效日期',
      value: 'licenseEndDate',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '包装规格',
      value: 'packedStandard',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '生产厂家',
      value: 'brandName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '生产厂家',
      value: 'brandId',
      type: 'select',
      show: false,
      disabled: true,
      list: 'brandList',
      filterable: true,
      clearable: true,
    },
  ],
  //控制信息
  controlFieldList: [
    {
      label: '近效期（天）',
      value: 'productNearlyEffective',
      type: 'number',
      required: true,
    },
    {
      label: '需要批号效期',
      value: 'needBatchNumber',
      type: 'radio-model',
      code: 'default_yes_or_no',
      required: true,
    },
    {
      label: '需要序列管理',
      value: 'needSequence',
      type: 'radio-model',
      code: 'default_yes_or_no',
      required: true,
    },
    {
      label: '以领定消',
      value: 'acquisitionReplaceConsume',
      type: 'radio-model',
      code: 'default_no_or_yes',
      required: true,
      labelTip: '科室领用即算消耗的产品',
    },
    {
      label: '是否议价',
      value: 'isBargaining',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },

    {
      label: '是否收费',
      value: 'isCharge',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '是否寄售',
      value: 'isConsignment',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '结算方式',
      value: 'settlementMethod',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'settlement_method',
      disabled: true,
    },
    {
      label: '手术跟台',
      value: 'withOperateTable',
      type: 'radio-model',
      code: 'default_no_or_yes',
      required: true,
      labelTip: '医院0库存，使用后结算的产品',
      show: false,
    },
    {
      label: '限制价格',
      value: 'isLimitPrice',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '采购限制价格',
      value: 'purchaseLimitPrice',
      type: 'number',
      max: 999999999999999,
      show: false,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '是否RFID管理',
      value: 'isRfidManage',
      type: 'radio-model',
      code: 'default_no_or_yes',
      show: true,
    },
    {
      label: '厂家理论测试次数',
      value: 'expectedUsageTimes',
      type: 'slot',
    },
    {
      label: '院内理论测试次数',
      value: 'hospitalExpectedUsageTimes',
      type: 'number',
      min: 1,
    },
    {
      label: '计费次数',
      value: 'chargeTimes',
      disabled: false,
      min: 1,
      type: 'number',
    },
    {
      label: '重点监控高值医用耗材',
      value: 'importantHighMaterial',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '是否集采',
      value: 'isCollectivePurchase',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '集采项目号',
      value: 'collectivePurchaseBatch',
      type: 'select-model',
      code: 'collective_purchase_batch',
      show: false
    },
    {
      label: '付款类型',
      value: 'paymentType',
      type: 'select-model',
      code: 'product_payment_type',
      show: false
    },
  ],
  // 挂网信息
  spreadFieldList: [
    {
      label: '是否挂网',
      value: 'isSunPurchase',
      type: 'radio-model',
      code: 'default_no_or_yes',
      labelTip: '挂网：阳光采购网',
    },
    {
      label: '挂网类型',
      value: 'networkType',
      show: false,
      type: 'select-model',
      clearable: true,
      code: 'network_type',
      checkDefault: true,
    },
    {
      label: '挂网产品类型',
      value: 'networkProductType',
      show: false,
      type: 'select-model',
      clearable: true,
      code: 'network_product_type',
      checkDefault: true,
    },
    {
      label: '商品代码',
      value: 'serialNum',
      show: false,
      type: 'input',
    },
    {
      label: '挂网耗材产品id',
      value: 'procureCatalogId',
      show: false,
      type: 'input',
    },
    {
      label: '挂网单位',
      value: 'networkUnit',
      show: false,
      type: 'input',
    },
    {
      label: '单位比例',
      value: 'networkUnitCoefficient',
      show: false,
      type: 'slot',
    },
    {
      label: '挂网单价',
      value: 'networkPrice',
      show: false,
      type: 'slot',
    },
  ],
  classifyFieldList: [
    {
      label: '发票类别',
      value: 'invoiceCategory',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'invoice_category',
    },
    {
      label: '病案类别',
      value: 'caseCategory',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'case_category',
    },
    { label: '产品分类', value: 'productCategoryId', type: 'slot' },
    {
      label: '财务科目',
      value: 'financialAccount',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'financial_account',
    },
    {
      label: '防疫物资',
      value: 'epidemicPrevention',
      type: 'radio-model',
      code: 'default_no_or_yes',
      required: true,
    },
    {
      label: '临采产品',
      value: 'temporaryPurch',
      type: 'radio-model',
      code: 'default_no_or_yes',
      required: true,
    },
    {
      label: '质管类型',
      value: 'dosageForm',
      type: 'select-model',
      clearable: true,
      checkDefault: false,
      code: 'new_dosage_form',
    },
    {
      label: '库存类别',
      value: 'inventoryCategories',
      type: 'select-model',
      code: 'inventory_categories',
      checkDefault: false,
      clearable: true,
    },
    {
      label: '项目分类',
      value: 'projectClassification',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'project_classification',
    },
    {
      label: '住院收据费用分类',
      value: 'classificationOfHospitalReceipts',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'classification_of_hospital_receipts',
    },
    {
      label: '门诊收据费用分类',
      value: 'outpatientReceiptFeeClassification',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'outpatient_receipt_fee_classification',
    },
    {
      label: '核算项目分类',
      value: 'accountingItemClassification',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'accounting_item_classification',
    },
    {
      label: '病案首页费用分类',
      value: 'medicalRecordsFirstPageCostClassification',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'medical_records_first_page_cost_classification',
    },
    {
      label: '项目等级',
      value: 'projectLevel',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'project_level',
    },
    {
      label: '收费项目会计子分类',
      value: 'chargeItemCategory',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'charge_item_category',
    },
    {
      label: '医嘱子类',
      value: 'adviceCategory',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'advice_category',
    },
    {
      label: '独立医嘱标记',
      value: 'independentAdviceMark',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'independent_advice_mark',
    },
    {
      label: '医嘱优先级',
      value: 'advicePriority',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'advice_priority',
    },
    {
      label: '新病案首页费用分类',
      value: 'newMedicalRecordsFirstPageCostClassification',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'new_medical_records_first_page_cost_classification',
    },
  ],
  medicareFieldList: [
    { label: '国家医保编码', value: 'nationCode', type: 'input' },
    { label: '省医保编码', value: 'provinceCode', type: 'input' },
    {
      label: '国家医保名称',
      value: 'nationHealthInsurance',
      type: 'input',
    },
  ],
  // 中标信息
  bidderFieldList: [
    {
      label: '试剂归属',
      value: 'reagentScope',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'reagent_scope',
    },
    { label: '是否中标', value: 'isWinning', type: 'slot' },
    {
      label: '中标批次',
      value: 'winningBatch',
      show: true,
      type: 'select-model',
      clearable: true,
      code: 'winning_batch',
    },
  ],
  rules: {
    mainCode: [
      {
        required: true,
        message: '请输入原厂主码',
        trigger: 'blur',
      },
    ],
    nationCode: [
      {
        required: true,
        message: '请输入国家医保编码',
        trigger: 'blur',
      },
    ],
    nationHealthInsurance: [
      {
        required: true,
        message: '请输入国家医保名称',
        trigger: 'blur',
      },
    ],
    commonName: [
      { required: true, message: '请输入通用名称', trigger: 'blur' },
    ],
    standard: [{ required: true, message: '请输入规格', trigger: 'blur' }],
    unitId: [{ required: true, message: '请选择计量单位', trigger: 'change' }],

    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    settlementMethod: [
      { required: true, message: '请选择结算方式', trigger: 'change' },
    ],
    purchaseLimitPrice: [
      {
        required: true,
        message: '请输入采购限制价格',
        trigger: 'change',
      },
    ],
    expectedUsageTimes: [
      {
        required: true,
        message: '请输入预期使用次数',
        trigger: 'change',
      },
    ],
    chargeTimes: [
      {
        required: true,
        message: '请输入计算次数',
        trigger: 'change',
      },
    ],
    hospitalExpectedUsageTimes: [
      {
        required: true,
        message: '请输入院内理论测试次数',
        trigger: 'change',
      },
    ],
    networkType: [
      { required: true, message: '请选择挂网类型', trigger: 'change' },
    ],
    networkProductType: [
      { required: true, message: '请选择挂网产品类型', trigger: 'change' },
    ],
    serialNum: [
      { required: true, message: '请输入挂网流水号', trigger: 'change' },
    ],
    networkUnit: [
      { required: true, message: '请输入挂网单位', trigger: 'change' },
    ],
    networkUnitCoefficient: [
      { required: true, validator: checkFrequency, trigger: 'change' },
    ],
    procureCatalogId: [
      { required: true, message: '请输入挂网耗材产品id', trigger: 'change' },
    ],
    qtyOperateMode: [
      {
        required: true,
        message: '请选择数量操作模式',
        trigger: 'change',
      },
    ],
    codeType: [
      { required: true, message: '请选择条码类型', trigger: 'change' },
    ],
    productType: [
      { required: true, message: '请选择产品类型', trigger: 'change' },
    ],
    // licenseNumber: [
    //   { required: true, message: '请选择证号', trigger: 'change' },
    // ],
    needBatchNumber: [
      {
        required: true,
        message: '请选择是否需要批号效期',
        trigger: 'change',
      },
    ],
    needSequence: [
      {
        required: true,
        message: '请选择是否需要序列管理',
        trigger: 'change',
      },
    ],
    code: [
      { required: true, message: '请输入编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    productNearlyEffective: [
      {
        required: true,
        type: 'number',
        min: 1,
        message: '请输入产品近效期',
        trigger: 'blur',
      },
    ],
    unitConvertCoefficient: [
      {
        required: true,
        type: 'number',
        min: 1,
        message: '请输入转换系数，最小值为1',
        trigger: 'blur',
      },
    ],
    isConsignment: [
      { required: true, message: '请选择是否寄售', trigger: 'change' },
    ],
    withOperateTable: [
      { required: true, message: '请选择是否手术跟台', trigger: 'change' },
    ],
    acquisitionReplaceConsume: [
      { required: true, message: '请选择是否以领定消', trigger: 'change' },
    ],
    epidemicPrevention: [
      { required: true, message: '请选择是否防疫物资', trigger: 'change' },
    ],
    temporaryPurch: [
      { required: true, message: '请选择是否临采产品', trigger: 'change' },
    ],
    isRfidManage: [
      { required: true, message: '请选择是否RFID管理', trigger: 'change' },
    ],
    isSunPurchase: [
      { required: true, message: '请选择是否挂网', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
const checkedWinning = ref(false)
const notCheckedWinning = ref(false)
const isDisableChargeTimes = computed(() => {
  // 无码或者批次码 和 整数模式禁用
  return (
    !formInfo.value.data.codeType ||
    formInfo.value.data.codeType == 1 ||
    !formInfo.value.data.codeType ||
    formInfo.value.data.codeType == 4 ||
    !formInfo.value.data.qtyOperateMode ||
    formInfo.value.data.qtyOperateMode == 0
  )
})
watch(
  () => formInfo.value.data.isCollectivePurchase,
  (value) => {
    if (value == 1) {
      showFieldListItem(true, 'collectivePurchaseBatch', 'controlFieldList')
      showFieldListItem(true, 'paymentType', 'controlFieldList')
    } else {
      showFieldListItem(false, 'collectivePurchaseBatch', 'controlFieldList')
      showFieldListItem(false, 'paymentType', 'controlFieldList')
      formInfo.value.data['collectivePurchaseBatch'] = ''
      formInfo.value.data['paymentType'] = ''
    }
  }
)
watch(
  () => isDisableChargeTimes.value,
  (value) => {
    if (value) {
      formInfo.value.data.chargeTimes = 1
    }
    formInfo.value.controlFieldList.forEach((element) => {
      if (element.value === 'chargeTimes') {
        element.disabled = value
      }
    })
  },
  {
    immediate: true,
  }
)
const selectLicenseInfo = ref({
  visible: false,
  query: {
    status: '1',
    licenseApplicationType: '1',
  },
})
const selectClassification = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectBarCodeRules = ref({
  visible: false,
  rules: undefined,
})
const listTypeInfo = ref({
  licenseList: [],
  brandList: [],
  unitList: [],
})
const options = ref([])
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const isFirstUpdate = ref(false)
const tableInfo = ref({
  data: [],
  selections: [],
  fieldList: [
    { label: '供应商名称', value: 'supplierName' },
    { label: '供应商编码', value: 'supplierCode' },
    {
      label: '供应商价格',
      value: 'price',
      type: 'slot',
      width: '220px',
    },
    { label: '是否默认', value: 'isDefaultValue' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '110',
    btList: [
      {
        label: '设为默认',
        event: setDefault,
        show: true,
        ifRender: function (row) {
          return row.isDefault !== 1
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('product:relationSupplierDel'),
      },
    ],
  },
})
const filterInfo = ref({
  query: {
    productId: props.detailId,
    sort: 'is_default desc,create_time desc',
  },
  list: [
    { type: 'slot', value: 'addSuppler' },
    { type: 'slot', value: 'remove' },
  ],
})
const supplierInfo = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    status: 1,
    searchType: 'org',
    searchField: 'supplierId',
    sort: 'create_time desc,id asc',
    supplierIdNotIn: '',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})

const unitvalue = computed(() => {
  let result = ''
  listTypeInfo.value.unitList.find((item) => {
    if (item.value === formInfo.value.data.unitId) {
      result = item.key
    }
  })
  return result
})
// // 收费产品医保信息是否必填'
// watch(
//   () => store.state.permission.systemConfig.is_need_medical_insurance,
//   (val) => {
//     console.log(val)
//     if(val == 1 && formInfo.value.data.isCharge == 1) {
//       formInfo.value.rules['nationCode'][0].required = true
//       formInfo.value.rules['nationHealthInsurance'][0].required = true
//     } else {
//       formInfo.value.rules['nationCode'][0].required = false
//       formInfo.value.rules['nationHealthInsurance'][0].required = false
//     }
//   },
//   {
//     immediate: true,
//     deep: true,
//   }
// )
// // '收费产品强制非以领定销'
// watch(
//   () => store.state.permission.systemConfig.is_need_acquisition_replace_consume,
//   (val) => {
//     if(val == 1 && formInfo.value.data.isCharge == 1) {
//       formInfo.value.data.acquisitionReplaceConsume = 0
//       formInfo.value.controlFieldList.forEach((element) => {
//         if (element.value === 'acquisitionReplaceConsume') {
//           element.disabled = true
//         }
//       })
//     } else {
//       formInfo.value.data.acquisitionReplaceConsume = ''
//       formInfo.value.controlFieldList.forEach((element) => {
//         if (element.value === 'acquisitionReplaceConsume') {
//           element.disabled = false
//         }
//       })
//     }
//   },
//   {
//     immediate: true,
//     deep: true,
//   }
// )
watch(
  () => formInfo.value.data.codeType,
  (value) => {
    if (!value) {
      return false
    }
    // showFieldListItem(value == 3 || value == 2, 'g1Value', 'fieldList')
    // showFieldListItem(value == 3 || value == 2, 'mainCode', 'fieldList')
    if (value == 1 || value == 4) {
      showFieldListItem(false, 'isRfidManage', 'controlFieldList')
      formInfo.value.data.isRfidManage = ''
    } else {
      showFieldListItem(true, 'isRfidManage', 'controlFieldList')
    }
    // if (value == 3 || value == 2) {
    if (value == 3 || value == 2) {
      formInfo.value.rules['mainCode'][0].required = true
    } else {
      formInfo.value.rules['mainCode'][0].required = false
    }
    if (formInfo.value.data.g1 && formInfo.value.data.g1.type === 'GS1_OTHER') {
      const eg = []
      formInfo.value.data.g1.coreProductRuleVOList.map((item) => {
        eg.push(
          String(
            '(' +
              item.ruleCode +
              ')' +
              stringFillCharacter(Number(item.ruleLength))
          )
        )
        delete item.disabledCode
        delete item.key
        return item
      })
      formInfo.value.data.g1 = formInfo.value.data.g1
      formInfo.value.data.g1Value = eg.toString().replace(/,/g, '')
      selectBarCodeRules.value.rules = formInfo.value.data.g1
    } else {
      let type = { type: 'GS1' }
      formInfo.value.data.g1 = type
      formInfo.value.data.g1Value = 'GS1规则'
      selectBarCodeRules.value.rules = type
    }
    // } else {
    //   formInfo.value.data.g1 = {}
    //   formInfo.value.data.g1Value = ''
    //   selectBarCodeRules.value.rules = {}
    //   // 取消mainCode rule  不然 不显示mainCode 但是会校验
    //   formInfo.value.rules['mainCode'][0].required = false
    // }
    if (value == 2) {
      formInfo.value.rules['mainCode'][0].required = false
    }
  }
)
watch(
  () => formInfo.value.data.needLicense,
  (value) => {
    if (value == 1) {
      // formInfo.value.rules.licenseNumber[0].required = true
      disabledFieldListItem(true, 'brandName')
      disabledFieldListItem(true, 'brandId')
      showFieldListItem(true, 'brandName', 'licenseFieldList')
      showFieldListItem(false, 'brandId', 'licenseFieldList')
      if (!isFirstUpdate.value) {
        formInfo.value.data['packedStandard'] = ''
        formInfo.value.data['brandName'] = ''
        formInfo.value.data['brandId'] = ''
        formInfo.value.data['licenseTypeValue'] = ''
        formInfo.value.data['licenseName'] = ''
        formInfo.value.data['licenseBeginDate'] = ''
        formInfo.value.data['licenseEndDate'] = ''
        formInfo.value.data['enName'] = ''
        formInfo.value.data['licenseId'] = -2
        formInfo.value.data['commonName'] = ''
        formInfo.value.data['licenseNumber'] = ''
      }
      formInfo.value.data['brandCode'] = ''
    } else if (value == 0) {
      // formInfo.value.rules.licenseNumber[0].required = false
      // if (formInfo.value.data.licenseNumber) {
      //   disabledFieldListItem(true, 'brandName')
      //   disabledFieldListItem(true, 'brandId')
      // } else {
      //   disabledFieldListItem(false, 'brandName')
      //   disabledFieldListItem(false, 'brandId')
      // }
      disabledFieldListItem(false, 'brandName')
      disabledFieldListItem(false, 'brandId')
      showFieldListItem(false, 'brandName', 'licenseFieldList')
      showFieldListItem(true, 'brandId', 'licenseFieldList')
      if (!isFirstUpdate.value) {
        formInfo.value.data['packedStandard'] = ''
        formInfo.value.data['brandName'] = ''
        formInfo.value.data['brandId'] = ''
        formInfo.value.data['licenseTypeValue'] = ''
        formInfo.value.data['licenseName'] = ''
        formInfo.value.data['licenseBeginDate'] = ''
        formInfo.value.data['licenseEndDate'] = ''
        formInfo.value.data['enName'] = ''
        formInfo.value.data['licenseId'] = -2
        formInfo.value.data['commonName'] = ''
        formInfo.value.data['licenseNumber'] = ''
      }
      formInfo.value.data['brandCode'] = ''
      isFirstUpdate.value = false
    }
  }
)
watch(
  () => formInfo.value.data.isLimitPrice,
  (value) => {
    if (value == 1) {
      showFieldListItem(true, 'purchaseLimitPrice', 'controlFieldList')
    } else {
      showFieldListItem(false, 'purchaseLimitPrice', 'controlFieldList')
      formInfo.value.data['purchaseLimitPrice'] = 0
    }
  }
)
watch(
  () => formInfo.value.data.isSunPurchase,
  (value) => {
    if (value == 1) {
      showFieldListItem(true, 'networkType', 'spreadFieldList')
      showFieldListItem(true, 'serialNum', 'spreadFieldList')
      showFieldListItem(true, 'networkUnit', 'spreadFieldList')
      showFieldListItem(true, 'networkUnitCoefficient', 'spreadFieldList')
      showFieldListItem(true, 'networkProductType', 'spreadFieldList')
      showFieldListItem(true, 'networkPrice', 'spreadFieldList')
      showFieldListItem(true, 'procureCatalogId', 'spreadFieldList')
      formInfo.value.data['isSunPurchaseValue'] = '是'
    } else {
      showFieldListItem(false, 'networkType', 'spreadFieldList')
      showFieldListItem(false, 'serialNum', 'spreadFieldList')
      showFieldListItem(false, 'networkUnit', 'spreadFieldList')
      showFieldListItem(false, 'networkUnitCoefficient', 'spreadFieldList')
      showFieldListItem(false, 'networkProductType', 'spreadFieldList')
      showFieldListItem(false, 'networkPrice', 'spreadFieldList')
      showFieldListItem(false, 'procureCatalogId', 'spreadFieldList')
      formInfo.value.data['networkType'] = -2
      formInfo.value.data['serialNum'] = ''
      formInfo.value.data['networkUnit'] = ''
      formInfo.value.data['systemUnitCoefficient'] = ''
      formInfo.value.data['networkUnitCoefficient'] = ''
      formInfo.value.data['networkProductType'] = ''
      formInfo.value.data['networkPrice'] = ''
      formInfo.value.data['procureCatalogId'] = ''
      formInfo.value.data['isSunPurchaseValue'] = '否'
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => formInfo.value.data.networkProductType,
  (val) => {
    setTimeout(() => {
      // 试剂
      if (formInfo.value.data.isSunPurchase == 1) {
        if (val == 1) {
          showFieldListItem(false, 'procureCatalogId', 'spreadFieldList')
          formInfo.value.data['procureCatalogId'] = ''
          formInfo.value.rules['procureCatalogId'][0].required = false
        } else if (val == 2) {
          showFieldListItem(true, 'procureCatalogId', 'spreadFieldList')
          formInfo.value.rules['procureCatalogId'][0].required = true
        }
      }
    }, 0)
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => formInfo.value.data.isBargaining,
  (value) => {
    if (value == 1) {
      formInfo.value.data['isBargainingValue'] = '是'
    } else {
      formInfo.value.data['isBargainingValue'] = '否'
    }
  }
)
watch(
  () => formInfo.value.data.isCharge,
  (value) => {
    if (
      value == 1 &&
      store.state.permission.systemConfig.is_need_medical_insurance == 1
    ) {
      formInfo.value.rules['nationCode'][0].required = true
      formInfo.value.rules['nationHealthInsurance'][0].required = true
    } else {
      formInfo.value.rules['nationCode'][0].required = false
      formInfo.value.rules['nationHealthInsurance'][0].required = false
    }

    if (
      value == 1 &&
      store.state.permission.systemConfig.is_need_acquisition_replace_consume ==
        1
    ) {
      formInfo.value.data.acquisitionReplaceConsume = 0
      formInfo.value.controlFieldList.forEach((element) => {
        if (element.value === 'acquisitionReplaceConsume') {
          element.disabled = true
        }
      })
    } else {
      formInfo.value.data.acquisitionReplaceConsume =
        formInfo.value.data.acquisitionReplaceConsume || 0
      formInfo.value.controlFieldList.forEach((element) => {
        if (element.value === 'acquisitionReplaceConsume') {
          element.disabled = false
        }
      })
    }
    if (value == 1) {
      formInfo.value.data['isChargeValue'] = '是'
    } else {
      formInfo.value.data['isChargeValue'] = '否'
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => formInfo.value.data.isConsignment,
  (value) => {
    if (value == 1) {
      formInfo.value.data['isConsignmentValue'] = '是'
      formInfo.value.data['settlementMethod'] = 1
      formInfo.value.data['settlementMethodValue'] = '消耗后结算'
      showFieldListItem(true, 'withOperateTable', 'controlFieldList')
    } else {
      formInfo.value.data['isConsignmentValue'] = '否'
      formInfo.value.data['settlementMethod'] = 2
      formInfo.value.data['settlementMethodValue'] = '入库后结算'
      formInfo.value.data['withOperateTable'] = 0
      showFieldListItem(false, 'withOperateTable', 'controlFieldList')
    }
  }
)
watch(
  () => formInfo.value.data.putShelfStatus,
  (value) => {
    if (value == 1) {
      formInfo.value.data['putShelfStatusValue'] = '是'
    } else {
      formInfo.value.data['putShelfStatusValue'] = '否'
    }
  }
)
watch(
  () => formInfo.value.data.qtyOperateMode,
  (value) => {
    showFieldListItem(value == 2, 'unitConvertCoefficient', 'fieldList')
  }
)
function changeExpectedUsageTimes(e) {
  if (!formInfo.value.data.hospitalExpectedUsageTimes) {
    formInfo.value.data.hospitalExpectedUsageTimes = e
  }
}
function changePrice(e, str) {
  props.$refs.tableForm.clearValidate(str)
}
function returnBack() {
  emits('returnModify')
}
//设置默认
function setDefault(row) {
  if (props.detailId && !props.isCopy) {
    setSupplierProductDefault(row.id).then((res) => {
      if (res && res.success) {
        getList()
      }
    })
  } else {
    tableInfo.value.data.forEach((item) => {
      item.isDefault = 0
      item.isDefaultValue = '否'
      if (item.supplierId === row.supplierId) {
        item.isDefault = 1
        item.isDefaultValue = '是'
      }
    })
  }
}
function remove(row) {
  if (row && row.supplierId) {
    if (props.detailId && !props.isCopy) {
      let ids = [row.id]
      reRemove(ids)
    } else {
      tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
      if (tableInfo.value.data.length) {
        let itemList = tableInfo.value.data.filter(
          (item) => item.isDefault == 1
        )
        if (!itemList.length) {
          tableInfo.value.data[0].isDefault = 1
          tableInfo.value.data[0].isDefaultValue = '是'
        }
      }
    }
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        if (props.detailId && !props.isCopy) {
          let ids = tableInfo.value.selections.map((item) => item.id)
          reRemove(ids)
        } else {
          tableInfo.value.data = tableInfo.value.data.filter(
            (item) => !tableInfo.value.selections.includes(item)
          )
          if (tableInfo.value.data.length) {
            let itemList = tableInfo.value.data.filter(
              (item) => item.isDefault == 1
            )
            if (!itemList.length) {
              tableInfo.value.data[0].isDefault = 1
              tableInfo.value.data[0].isDefaultValue = '是'
            }
          }
        }
      })
  }
}
function reRemove(ids) {
  productsRelationSupplierDel(ids, props.detailId).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function getList() {
  getSupplierProductAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data && data.length) {
        data.forEach((item) => {
          item.isDefault = item.isDefault ? item.isDefault : 0
          item.isDefaultValue = item.isDefault ? item.isDefaultValue : '否'
        })
      }
      tableInfo.value.data = data
    }
  })
}
function addSuppler() {
  supplierInfo.value.visible = true
  let ids = tableInfo.value.data.map((item) => item.supplierId)
  supplierInfo.value.query.supplierIdNotIn = ids.length ? ids.toString() : ''
}
function showSupplier(row) {
  proxy.$router.push({
    name: 'supplier',
    params: {
      supplierId: row.supplierId,
    },
  })
}
function supplierCallback(data) {
  if (data && data.length) {
    let arr = data.map((item) => {
      return {
        price: item.price || 0,
        supplierName: item.supplierName,
        supplierCode: item.supplierCode,
        supplierId: item.supplierId,
        contact: item.contact,
        contactNumber: item.contactNumber,
        expectDeliveryDay: item.expectDeliveryDay,
        isDefault: 0,
        isDefaultValue: '否',
      }
    })
    if (props.detailId && !props.isCopy) {
      let params = {
        id: props.detailId,
        supplierList: arr,
      }
      productsRelationSupplier(params).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    } else {
      tableInfo.value.data = arr.concat(tableInfo.value.data)
      let itemList = tableInfo.value.data.filter((item) => item.isDefault == 1)
      if (!itemList.length) {
        tableInfo.value.data[0].isDefault = 1
        tableInfo.value.data[0].isDefaultValue = '是'
      }
    }
  }
}

function handleResponse(response, file) {
  return file
}

function openCategoryList() {
  selectClassification.value.visible = true
}
function selectClassificationCallback(data) {
  if (data) {
    formInfo.value.data['productCategoryId'] = data.id
    if (formInfo.value.data.productCategoryId === -2) {
      formInfo.value.data['productCategoryValue'] = ''
    } else {
      formInfo.value.data['productCategoryValue'] = data.name
    }
  } else {
    formInfo.value.data['productCategoryValue'] = ''
    formInfo.value.data['productCategoryId'] = -2
  }
  selectClassification.value.visible = false
}
function showFieldListItem(show, nameValue, str) {
  // let fieldList = formInfo.value[str]
  formInfo.value[str].forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function disabledFieldListItem(enable, nameValue) {
  // let fieldList = formInfo.value.licenseFieldList
  formInfo.value.licenseFieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.disabled = enable
    }
  })
}
function showPlaceholderFieldListItem(enable, nameValue) {
  // let fieldList = formInfo.value.fieldList
  formInfo.value.fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.placeholder = enable === false ? enable : ''
    }
  })
}
function openLicenseList() {
  selectLicenseInfo.value.visible = true
}
function openBarCodeRules() {
  selectBarCodeRules.value.visible = true
}
function onSelectBarCodeRules(data) {
  formInfo.value.data = {
    ...formInfo.value.data,
    g1: data.g1,
    g1Value: data.value,
    originType: data.g1.type,
  }
  selectBarCodeRules.value.rules = data.g1
}
//获取厂家列表
function getBrandList() {
  getBrandAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.brandList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
//获取计量单位列表
function getUnitList() {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
function getClassficationTree() {
  getProductCategoryTree().then((res) => {
    if (res && res.data && res.data.length > 0) {
      options.value = res.data.children
    }
  })
}
// 选择征照
function selectLicense(data) {
  const _formInfo = formInfo.value
  proxy.$nextTick(function () {
    if (data) {
      _formInfo.data = {
        ..._formInfo.data,
        licenseNumber: data.licenseNumber,
        licenseTypeValue: data.licenseTypeValue,
        licenseName: data.licenseName,
        licenseBeginDate: data.licenseBeginDate,
        licenseEndDate: data.licenseEndDate,
        brandName: data.brandName,
        brandCode: data.brandCode,
        enName: data.enName,
        packedStandard: data.packedStandard,
        licenseId: data.id,
        commonName: data.licenseName,
        brandId: data.brand,
        storageCondition: data.storageCondition || '',
      }
      disabledFieldListItem(true, 'brandName')
      disabledFieldListItem(true, 'brandId')
    } else {
      _formInfo.data = {
        ..._formInfo.data,
        licenseNumber: '',
        licenseTypeValue: '',
        licenseName: '',
        licenseBeginDate: '',
        licenseEndDate: '',
        brandName: '',
        brandCode: '',
        enName: '',
        packedStandard: '',
        licenseId: -2,
        commonName: '',
        brandId: '',
      }
      if (formInfo.value.data.needLicense == 0) {
        disabledFieldListItem(false, 'brandName')
        disabledFieldListItem(false, 'brandId')
      } else {
        disabledFieldListItem(true, 'brandName')
        disabledFieldListItem(true, 'brandId')
      }
    }
  })
}
function save() {
  const _formInfo = formInfo.value
  let formRef = [
    formInfo.value.ref,
    formInfo.value.licenseRef,
    formInfo.value.controlRef,
    formInfo.value.spreadRef,
    formInfo.value.classifyRef,
    formInfo.value.medicareRef,
    formInfo.value.bidderRef,
    proxy.$refs.tableForm,
  ]
  proxy.$fn.checkForm(formRef).then(() => {
    let api
    let itemList = tableInfo.value.data.filter((item) => item.isDefault == 1)
    if (
      tableInfo.value.data &&
      tableInfo.value.data.length &&
      !itemList.length
    ) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请设置默认供应商',
      })
      return
    }
    let isWinning
    if (checkedWinning.value) {
      isWinning = 1
    } else if (notCheckedWinning.value) {
      isWinning = 0
    } else {
      isWinning = -2
    }
    const params = {
      ..._formInfo.data,
      brandId: _formInfo.data.brandId ? _formInfo.data.brandId : -2,
      isWinning,
      unitConvertCoefficient:
        _formInfo.data.qtyOperateMode == 2
          ? _formInfo.data.unitConvertCoefficient
          : 1,
      type: 0,
      projectClassification:
        _formInfo.data.projectClassification == ''
          ? -2
          : _formInfo.data.projectClassification,
      supplierList: tableInfo.value.data,
    }
    const type = props.type
    if (type === 'create') {
      api = createProduct
    } else if (type === 'update') {
      api = updateProduct
    } else {
      return
    }
    params.classifyId = -1
    validateNetworkInfoDuplicated(params).then(res => {
      if(res.code === 200) {
        proxy
          .$handleAPI(type, api, params)
          .then((res) => {
            if (res.success) {
              showDialog.value = false
              emits('returnModify', false)
            }
          })
          .catch(() => {})
      }
    })
  })
}
function getDetails() {
  getProductById(props.detailId).then((resp) => {
    if (resp && resp.success) {
      if (props.isCopy) {
        resp.data.code = ''
        resp.data.hisCode = ''
        resp.data.id = null
      }
      let isWinning = resp.data.isWinning
      if (isWinning === 1) {
        checkedWinning.value = true
      } else if (isWinning === 0) {
        notCheckedWinning.value = true
      } else {
        checkedWinning.value = false
        notCheckedWinning.value = false
      }
      formInfo.value.data = {
        ...resp.data,
        brandId: resp.data.brandId === -2 ? '' : resp.data.brandId,
        collectivePurchaseBatch: resp.data.collectivePurchaseBatch == -2 ? '' : resp.data.collectivePurchaseBatch,
        paymentType: resp.data.paymentType == -2 ? '' : resp.data.paymentType,
        supplierList: [],
      }
    }
  })
}
function stringFillCharacter(length) {
  return new Array(length + 1).join('x')
}
function getStatus() {
  getCoreCodeStatus({ codeType: '2' }).then((res) => {
    showFieldListItem(!res.data, 'code', 'fieldList')
    formInfo.value.rules.code[1].required = !res.data
  })
}
function getCoreSystemConfig() {
  let param = {
    systemConfigCodeMult: 'qty_operate_mode,code_type_support',
  }
  let fieldList = formInfo.value.fieldList
  getCoreSystemConfigAll(param).then((res) => {
    if (res && res.success && res.data && res.data.length) {
      res.data.forEach((item) => {
        formInfo.value.systemConfig[item.systemConfigCode] = Number(item.value)
        if (item.systemConfigCode === 'qty_operate_mode') {
          showFieldListItem(
            (props.detailId
              ? formInfo.value.data.qtyOperateMode
              : item.value) == 2,
            'unitConvertCoefficient',
            'fieldList'
          )
        }
      })
    }
  })
}
function checkedWinningFunc() {
  if (checkedWinning.value) {
    notCheckedWinning.value = false
    formInfo.value.data.isWinning = 1
  }
}
function notCheckedWinningFunc() {
  if (notCheckedWinning.value) {
    checkedWinning.value = false
    formInfo.value.data.isWinning = 0
  }
}
onMounted(() => {
  let financialAccount = [
    { required: true, message: '请选择财务科目', trigger: 'change' },
  ]
  let is_need_financial_account =
    proxy.$store.state.permission.systemConfig.is_need_financial_account
  if (is_need_financial_account == 1) {
    formInfo.value.rules.financialAccount = financialAccount
  } else {
    delete formInfo.value.rules.financialAccount
  }
  getBrandList()
  getClassficationTree()
  getUnitList()
  getStatus()
  getCoreSystemConfig()
  if (props.detailId) {
    getDetails()
    if (!props.isCopy) {
      getList()
    }
    isFirstUpdate.value = true
  }
})
</script>

<style scoped></style>
